package com.jnu.student.myfirstapplication.ui;

import android.content.Context;
import android.util.Log;

import com.jnu.student.myfirstapplication.data.TaskItem;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class DataSave {
    final String DATA_FILENAME;      // 将数据保存在这个文件里
    public DataSave(String date_file) {this.DATA_FILENAME = date_file;}
    public ArrayList<TaskItem> LoadItems(Context context) {
        ArrayList<TaskItem> data = new ArrayList<>();
        try {
            FileInputStream fileIn = context.openFileInput(DATA_FILENAME);    // 读取文件
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);       // 反序列化
            data = (ArrayList<TaskItem>) objectIn.readObject();     // 加载数据
            objectIn.close();
            fileIn.close();
            Log.d("Serialization", "数据成功加载。共有" + data.size()+"个item。");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return data;
    }

    public void SaveItems(Context context, ArrayList<TaskItem> shopItems) {
        try {
            FileOutputStream fileOut = context.openFileOutput(DATA_FILENAME, Context.MODE_PRIVATE); // 写入文件
            ObjectOutputStream out = new ObjectOutputStream(fileOut);       // 序列化
            out.writeObject(shopItems);     // 将数据写入文件
            out.close();
            fileOut.close();
            Log.d("Serialization", "数据已完成序列化并保存。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
